package com.gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class MyFrame extends JFrame {
	private JTextField field;
	private JTextField field2;

	private JButton btnStart1;
	private JButton btnStart2;
	private JButton btnStop1;
	private JButton btnStop2;

	boolean control1;
	boolean control2;

	public MyFrame() {

		setLayout(new GridLayout(3, 2, 10, 10));

		add(getField());
		add(getField2());
		add(getBtnStart1());
		add(getBtnStart2());
		add(getBtnStop1());
		add(getBtnStop2());

		setSize(200, 150);
		setVisible(true);

		setDefaultCloseOperation(EXIT_ON_CLOSE);

		// dongu();

		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				dongu();
			}
		}).start();

	}

	void dongu() {
		int count1 = 0;
		int count2 = 0;
		while (true) {
			System.out.println("1");

			if (control1) {
				// System.out.println(count1++);
				getField().setText("" + count1++);
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (control2) {
				// System.out.println(count2++);
				getField2().setText("" + count2++);
			}
		}
	}

	public JTextField getField() {
		if (field == null) {
			field = new JTextField();
		}
		return field;
	}

	public JTextField getField2() {
		if (field2 == null) {
			field2 = new JTextField();
		}
		return field2;
	}

	public JButton getBtnStart1() {
		if (btnStart1 == null) {
			btnStart1 = new JButton("Start1");
			btnStart1.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					control1 = true;
				}
			});
		}
		return btnStart1;
	}

	public JButton getBtnStart2() {
		if (btnStart2 == null) {
			btnStart2 = new JButton("Start2");
			btnStart2.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					control2 = true;
				}
			});
		}
		return btnStart2;
	}

	public JButton getBtnStop1() {
		if (btnStop1 == null) {
			btnStop1 = new JButton("Stop1");
			btnStop1.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					control1 = false;
				}
			});
		}
		return btnStop1;
	}

	public JButton getBtnStop2() {
		if (btnStop2 == null) {
			btnStop2 = new JButton("Stop2");
			btnStop2.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					control2 = false;
				}
			});
		}
		return btnStop2;
	}
}
